package io.jnet.common.bufstorage.impl;

import com.jfireframework.baseutil.collection.buffer.ByteBuf;
import com.jfireframework.baseutil.concurrent.MPSCQueue;
import io.jnet.common.bufstorage.BufStorage;

public class QueueBufStorage implements BufStorage
{
    private MPSCQueue<ByteBuf<?>> storage = new MPSCQueue<>();
    
    @Override
    public StorageType type()
    {
        return StorageType.queue;
    }
    
    @Override
    public boolean putBuf(ByteBuf<?> buf)
    {
        storage.offer(buf);
        return true;
    }
    
    @Override
    public ByteBuf<?> next()
    {
        return storage.poll();
    }
    
    @Override
    public int batchNext(ByteBuf<?>[] store, int max)
    {
        int i = 0;
        for (; i < max; i++)
        {
            ByteBuf<?> buf = storage.poll();
            if (buf != null)
            {
                store[i] = buf;
            }
            else
            {
                break;
            }
        }
        return i;
    }
    
    @Override
    public boolean canPutMore()
    {
        return true;
    }
    
    @Override
    public boolean isEmpty()
    {
        return storage.isEmpty();
    }
    
}
